package com.borrow.jiemihua.mainUI.fragment;


import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.borrow.jiemihua.R;
import com.borrow.jiemihua.base.BaseConstant;
import com.borrow.jiemihua.base.BaseRVAdapter;
import com.borrow.jiemihua.base.BaseViewHolder;
import com.borrow.jiemihua.base.URLConstant;
import com.borrow.jiemihua.bean.PlatLiShiJDBean;
import com.borrow.jiemihua.bean.PlatformDetailsBean;
import com.borrow.jiemihua.mainUI.activity.ApplyWebViewActivity;
import com.borrow.jiemihua.mainUI.activity.LoginRegister.LoginActivity;
import com.borrow.jiemihua.utils.SharedPreferencesUtils;
import com.borrow.jiemihua.utils.dialog.ShowAlertDialog;
import com.borrow.jiemihua.utils.xutils3.MyCallBack;
import com.borrow.jiemihua.utils.xutils3.XUtil;
import com.borrow.jiemihua.view.dialogView.BaseBottomView;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.Event;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
@ContentView(R.layout.activity_platform_details)
public class HotFragment extends Fragment {

//    private WebView webView;
//    private ImageView imgbtn_left;
//    private TextView tv_top_title;
//    private RelativeLayout rl_iv_right;
//    private ImageView iv_right;

    @ViewInject(R.id.rl_iv_right)
    private RelativeLayout rl_iv_right;
    @ViewInject(R.id.iv_right)
    private ImageView iv_right;
    @ViewInject(R.id.imgbtn_left)
    private ImageView imgbtn_left;

    @ViewInject(R.id.tv_top_title)
    private TextView tv_top_title;
    @ViewInject(R.id.tv_num)
    private TextView tv_num;

    @ViewInject(R.id.tv_qi_time)
    private TextView tv_qi_time;
    @ViewInject(R.id.et_je)
    private EditText et_je;
    @ViewInject(R.id.iv_image)
    private ImageView iv_image;
    @ViewInject(R.id.tv_pt_name)
    private TextView tv_pt_name;
    @ViewInject(R.id.tv_dklx)
    private TextView tv_dklx;
    @ViewInject(R.id.iv_stars1)
    private ImageView iv_stars1;
    @ViewInject(R.id.iv_stars2)
    private ImageView iv_stars2;
    @ViewInject(R.id.iv_stars3)
    private ImageView iv_stars3;
    @ViewInject(R.id.iv_stars4)
    private ImageView iv_stars4;
    @ViewInject(R.id.iv_stars5)
    private ImageView iv_stars5;
    @ViewInject(R.id.tv_dkfw)
    private TextView tv_dkfw;
    @ViewInject(R.id.tv_ckll)
    private TextView tv_ckll;
    @ViewInject(R.id.tv_dk_time)
    private TextView tv_dk_time;
    @ViewInject(R.id.tv_sqtj)
    private TextView tv_sqtj;
    @ViewInject(R.id.tv_sxcl)
    private TextView tv_sxcl;

    @ViewInject(R.id.tv_gg1)
    private TextView tv_gg1;
    @ViewInject(R.id.tv_gg2)
    private TextView tv_gg2;
    @ViewInject(R.id.tv_gg3)
    private TextView tv_gg3;
    @ViewInject(R.id.tv_gg1_time)
    private TextView tv_gg1_time;
    @ViewInject(R.id.tv_gg2_time)
    private TextView tv_gg2_time;
    @ViewInject(R.id.tv_gg3_time)
    private TextView tv_gg3_time;
    private String terraceId;

    private PlatformDetailsBean.DataBean dataBean=new PlatformDetailsBean.DataBean();

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return x.view().inject(this, inflater, container);
    }
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        upGetH5Data();
        initView();
        super.onActivityCreated(savedInstanceState);
    }

//        @Override
//    public View initView(LayoutInflater inflater) {
//        view = inflater.inflate(R.layout.fragment_hot, null);
//        view = inflater.inflate(R.layout.activity_platform_details, null);
//
//
//        initData();
//        initViews();
//        upGetH5Data();
//        return view;
//    }

    private void initView(){
//        webView= (WebView) view.findViewById(R.id.webView);
//        imgbtn_left= (ImageView) view.findViewById(R.id.imgbtn_left);
//        tv_top_title= (TextView) view.findViewById(R.id.tv_top_title);
//        rl_iv_right= (RelativeLayout) view.findViewById(R.id.rl_iv_right);
//        iv_right= (ImageView) view.findViewById(R.id.iv_right);
        iv_right.setImageResource(R.drawable.shape2xsx);
        rl_iv_right.setVisibility(View.VISIBLE);
        tv_top_title.setText("");
        imgbtn_left.setVisibility(View.GONE);
        rl_iv_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                upGetH5Data();
            }
        });
    }
    private void upGetH5Data() {
//        showDialog();
        XUtil.Get(URLConstant.HOTH5,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==热门GetH5",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if(res.equals("1")){
                        terraceId = jsonObject.optString("data");
//                        WebSettings settings = webView.getSettings();
//                        settings.setJavaScriptEnabled(true);
//                        settings.setUseWideViewPort(false);
//                        settings.setJavaScriptCanOpenWindowsAutomatically(true);
//                        settings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
//                        if (webView != null) {
//                            webView.setWebViewClient(new WebViewClient() {
//                                @Override
//                                public void onPageFinished(WebView view, String url) {
//                                    super.onPageFinished(view, url);
//                                }
//                            });
//                            webView.getSettings().setJavaScriptEnabled(true);
//                            webView.loadUrl(url);
//                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                upPTDetailsData();
                upMessageData();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);

                ex.printStackTrace();
            }
        });
    }
    private void setData(){
        Glide.with(this).load(dataBean.getLogo()).into(iv_image);
        tv_pt_name.setText(dataBean.getName());
        if(dataBean.getLendType()==1){
            tv_dklx.setText("现金贷");
        } else if(dataBean.getLendType()==2){
            tv_dklx.setText("信用贷");
        }else if(dataBean.getLendType()==2){
            tv_dklx.setText("大额贷");
        }
        String maxM=String.valueOf(dataBean.getMaxAmount());
        String minM=String.valueOf(dataBean.getMinAmount());
        String manED = "";
        String minED = "";
        DecimalFormat df   = new DecimalFormat("######0.0");
        if(!maxM.equals("")){
            if (maxM.length()>=5){
                String str=String.valueOf(df.format(Double.parseDouble(maxM)/10000));
                int ii=Integer.parseInt(str.substring(str.length()-1,str.length()));
                if(ii>0){
                    manED=str+"万";
                }else{
                    manED=String.valueOf(Integer.parseInt(maxM)/10000)+"万";
                }
            }else if(maxM.length()==4){
                String str=String.valueOf(df.format(Double.parseDouble(maxM)/1000));
                int ii=Integer.parseInt(str.substring(str.length()-1,str.length()));
                if(ii>0){
                    manED=str+"千";
                }else{
                    manED=String.valueOf(Integer.parseInt(maxM)/1000)+"千";
                }
            }else if(maxM.length()<4){
                manED=maxM;
            }
        }
        if(!minM.equals("")){
            if (minM.length()>=5){
                String str=String.valueOf(df.format(Double.parseDouble(minM)/10000));
                int ii=Integer.parseInt(str.substring(str.length()-1,str.length()));
                if(ii>0){
                    minED=str+"万";
                }else{
                    minED=String.valueOf(Integer.parseInt(minM)/10000)+"万";
                }
//                minED=String.valueOf(Double.parseDouble(minM)/10000)+"万";
            }else if(minM.length()==4){
                String str=String.valueOf(df.format(Double.parseDouble(minM)/1000));
                int ii=Integer.parseInt(str.substring(str.length()-1,str.length()));
                if(ii>0){
                    minED=str+"千";
                }else{
                    minED=String.valueOf(Integer.parseInt(minM)/1000)+"千";
                }
//                minED=String.valueOf(Double.parseDouble(minM)/1000)+"千";
            }else if(minM.length()<4){
                minED=minM;
            }
        }
        tv_dkfw.setText(minM+"元"+"~"+maxM+"元");
        tv_ckll.setText(dataBean.getRateStr());
        tv_top_title.setText(dataBean.getName());
        tv_num.setText(dataBean.getApplyForCount()+"");
//        String time=String.valueOf(dataBean.getQuickestTime()/60);
        tv_dk_time.setText(dataBean.getQuickestTimeStr());
        tv_sqtj.setText(dataBean.getApplyForCondition());
        tv_sxcl.setText(dataBean.getNeedInformation());
        if(dataBean.getSuccessRate()<2){
            iv_stars1.setVisibility(View.VISIBLE);
            iv_stars2.setVisibility(View.GONE);
            iv_stars3.setVisibility(View.GONE);
            iv_stars4.setVisibility(View.GONE);
            iv_stars5.setVisibility(View.GONE);
        }else if(dataBean.getSuccessRate()==2){
            iv_stars1.setVisibility(View.VISIBLE);
            iv_stars2.setVisibility(View.VISIBLE);
            iv_stars3.setVisibility(View.GONE);
            iv_stars4.setVisibility(View.GONE);
            iv_stars5.setVisibility(View.GONE);
        } else if(dataBean.getSuccessRate()==3){
            iv_stars1.setVisibility(View.VISIBLE);
            iv_stars2.setVisibility(View.VISIBLE);
            iv_stars3.setVisibility(View.VISIBLE);
            iv_stars4.setVisibility(View.GONE);
            iv_stars5.setVisibility(View.GONE);
        }else if(dataBean.getSuccessRate()==4){
            iv_stars1.setVisibility(View.VISIBLE);
            iv_stars2.setVisibility(View.VISIBLE);
            iv_stars3.setVisibility(View.VISIBLE);
            iv_stars4.setVisibility(View.VISIBLE);
            iv_stars5.setVisibility(View.GONE);
        }else if(dataBean.getSuccessRate()>4){
            iv_stars1.setVisibility(View.VISIBLE);
            iv_stars2.setVisibility(View.VISIBLE);
            iv_stars3.setVisibility(View.VISIBLE);
            iv_stars4.setVisibility(View.VISIBLE);
            iv_stars5.setVisibility(View.VISIBLE);
        }
    }
    @Event(value = {R.id.ll_qixz,R.id.tv_ljsq},type= View.OnClickListener.class)
    private void getEvent(View view) {
        switch (view.getId()) {
            case R.id.ll_qixz:
                initsetJEBX();
                break;
            case R.id.tv_ljsq:
                String userid4 = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
                if (!userid4.equals("")&&userid4!=null){
                    upApplyData();
                    upPTTJData();
//                    startActivity(new Intent(this,ApplyNowActivity.class)
//                            .putExtra("url",dataBean.getUrl())
//                            .putExtra("name",dataBean.getName())
//                            .putExtra("money",et_je.getText().toString().trim())
//                            .putExtra("time",tv_qi_time.getText().toString().trim())
//                            .putExtra("qiTime",dataBean.getChoosableRepaymentTimeLimit()));
                }else{
                    startActivity(new Intent(getActivity(),LoginActivity.class));
                }
                break;
        }
    }
    private List listTime;
    private  void addTime(){
        String str =dataBean.getChoosableRepaymentTimeLimit();
        String[] arr = str.split(",");//分割字符串得到数组
        listTime = java.util.Arrays.asList(arr);//字符数组转list
        if(listTime.size()>0){
            if(dataBean.getUnitOfRepaymentTime()==0){//天
                tv_qi_time.setText(listTime.get(0)+"天");
            }else{
                int qixian = Integer.parseInt((String) listTime.get(0));
                tv_qi_time.setText(qixian/30+"月");
            }
        }else{
            if(dataBean.getUnitOfRepaymentTime()==0){//天
                tv_qi_time.setText(7+"天");
            }else{
                tv_qi_time.setText(7/30+"月");
            }
        }

    }
    private void initsetJEBX(){
        final BaseBottomView bottomView = new BaseBottomView(getActivity(), R.layout.platform_details_time);
        bottomView.setCancelable(true);
        bottomView.show();
        RecyclerView recycler_view= (RecyclerView) bottomView.findViewById(R.id.recycler_view);
        recycler_view.setLayoutManager(new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false));
        recycler_view.setAdapter(new BaseRVAdapter(getActivity(),listTime) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.platform_time_item;
            }
            @Override
            public void onBind(final BaseViewHolder holder, final int position) {
                if(dataBean.getUnitOfRepaymentTime()==0){//天
                    holder.getTextView(R.id.tv_time_litem).setText(listTime.get(position)+"天");
                }else{
                    int qixian = Integer.parseInt((String) listTime.get(position));
                    holder.getTextView(R.id.tv_time_litem).setText(qixian/30+"月");

                }
                holder.getTextView(R.id.tv_time_litem).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if(dataBean.getUnitOfRepaymentTime()==0){//天
                            tv_qi_time.setText(listTime.get(position)+"天");
                            holder.getTextView(R.id.tv_time_litem).setText(listTime.get(position)+"天");
                        }else{
                            int qixian = Integer.parseInt((String) listTime.get(position));
                            tv_qi_time.setText(qixian/30+"月");

                        }
                        bottomView.dismiss();
                    }
                });

            }
        });
        bottomView.findViewById(R.id.tv_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomView.dismiss();
            }
        });
    }
    private void upPTTJData(){
        Map<String,String> map=new HashMap<>();
        map.put("terraceId",terraceId);
        showDialog();
        XUtil.Get(URLConstant.ADDPEOPLE,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==获取增加盛情人数",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    String data = jsonObject.optString("data");
                    if(res.equals("1")){

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
                startActivity(new Intent(getActivity(),ApplyWebViewActivity.class)
                        .putExtra("name",dataBean.getName())
                        .putExtra("url",dataBean.getUrl()));
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }
    private void upApplyData(){
        Map<String,Object> map=new HashMap<>();
        String userid = SharedPreferencesUtils.getString(getActivity(), BaseConstant.SPConstant.USERID, "");
        map.put("userId",userid);
        map.put("terraceId",terraceId);
        map.put("applyForAmount",et_je.getText().toString().trim());
        String time =tv_qi_time.getText().toString().trim();
        map.put("timeLimit",time.substring(0,time.length()-1)+"");

//        showDialog();
        XUtil.Post(URLConstant.APPLY_DAIKUAN,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                Log.i("===申请贷款",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if(res.equals("1")){

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
//                closeDialog();
            }
        });
    }
    private void upPTDetailsData(){
        Map<String,String> map=new HashMap<>();
        map.put("terraceId",terraceId);
//        Log.e("==terraceId",terraceId);
        showDialog();
        XUtil.Get(URLConstant.PINGTAIXIANGQING,map,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
//                Log.i("==平台详情",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if(res.equals("1")){
                        Gson gson=new Gson();
                        PlatformDetailsBean platformDetailsBean=gson.fromJson(result, PlatformDetailsBean.class);
                        dataBean=platformDetailsBean.getData();
                        setData();
                        addTime();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
                closeDialog();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
                closeDialog();
            }
        });
    }
    private void upMessageData() {
        Map<String,String> map=new HashMap<>();
        map.put("terraceId",terraceId);
        map.put("page","1");
//        map.put("pageSize","3");
        XUtil.Get(URLConstant.PINGTAILISHIJIEDAI,new MyCallBack<String>(){
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                Log.i("==历史借贷",result);
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    String res = jsonObject.optString("isSuccess");
                    if(res.equals("1")){
                        Gson gson=new Gson();
                        PlatLiShiJDBean borrowGBBean=gson.fromJson(result, PlatLiShiJDBean.class);
                        List<PlatLiShiJDBean.DataBean>  dataBeanList=borrowGBBean.getData();
                        if(dataBeanList.size()==3){
                            tv_gg1.setText(dataBeanList.get(0).getCellphone()+"在"+dataBeanList.get(0).getTerraceName()+"成功借款"+dataBeanList.get(0).getAmount()+"元");
                            tv_gg2.setText(dataBeanList.get(1).getCellphone()+"在"+dataBeanList.get(1).getTerraceName()+"成功借款"+dataBeanList.get(1).getAmount()+"元");
                            tv_gg3.setText(dataBeanList.get(2).getCellphone()+"在"+dataBeanList.get(2).getTerraceName()+"成功借款"+dataBeanList.get(2).getAmount()+"元");
                            tv_gg1_time.setText(dataBeanList.get(0).getCreateTime());
                            tv_gg2_time.setText(dataBeanList.get(1).getCreateTime());
                            tv_gg3_time.setText(dataBeanList.get(2).getCreateTime());
                        }else  if(dataBeanList.size()==2){
                            tv_gg1.setText(dataBeanList.get(0).getCellphone()+"在"+dataBeanList.get(0).getTerraceName()+"成功借款"+dataBeanList.get(0).getAmount()+"元");
                            tv_gg2.setText(dataBeanList.get(1).getCellphone()+"在"+dataBeanList.get(1).getTerraceName()+"成功借款"+dataBeanList.get(1).getAmount()+"元");
                            tv_gg3.setText("150******222在及贷成功借到1000元");
                            tv_gg1_time.setText(dataBeanList.get(0).getCreateTime());
                            tv_gg2_time.setText(dataBeanList.get(1).getCreateTime());
                            tv_gg3_time.setText("12-1 11:30");
                        }else if(dataBeanList.size()==1){
                            tv_gg1.setText(dataBeanList.get(0).getCellphone()+"在"+dataBeanList.get(0).getTerraceName()+"成功借款"+dataBeanList.get(0).getAmount()+"元");
                            tv_gg2.setText("183******432在及贷成功借到1500元");
                            tv_gg3.setText("176******526在及贷成功借到3000元");
                            tv_gg1_time.setText(dataBeanList.get(0).getCreateTime());
                            tv_gg2_time.setText("12-23 11:10");
                            tv_gg3_time.setText("12-11 14:30");
                        }else{
                            tv_gg1.setText("150******222在及贷成功借到1000元");
                            tv_gg2.setText("183******432在及贷成功借到1500元");
                            tv_gg3.setText("176******526在及贷成功借到3000元");
                            tv_gg1_time.setText("2-23 01:10");
                            tv_gg2_time.setText("12-23 11:10");
                            tv_gg3_time.setText("12-11 14:30");
                        }

                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFinished() {
                super.onFinished();
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                ex.printStackTrace();
            }
        });
    }
    protected Dialog dialog;

    public void showDialog() {

        if (null == dialog) {
            dialog = ShowAlertDialog.loadingDialog(getActivity());
        }
        dialog.show();

    }

    public void closeDialog() {
        if (null != dialog) {
            dialog.dismiss();
        }
        //    hideProgress();

    }
//    @Override
//    protected void onResume() {
//        super.onResume();
//        upPTDetailsData();
//        upMessageData();
//    }
}
